import os
from configparser import ConfigParser as CP

import pymysql


class Config(CP):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def read_config(self, path):
        path = self.read(path)
        return path

    def get_config(self):
        self.read(path)
        config = self
        MYSQL_DB_NAME = config.get('MYSQL', 'database')
        MYSQL_HOST = config.get('MYSQL', 'host')
        MYSQL_PORT = int(config.get('MYSQL', 'port'))
        MYSQL_USER = config.get('MYSQL', 'user')
        MYSQL_PASSWORD = config.get('MYSQL', 'password')
        config_dict = {
            'host': MYSQL_HOST,
            'port': MYSQL_PORT,
            'user': MYSQL_USER,
            'password': MYSQL_PASSWORD,
            'database': MYSQL_DB_NAME,
            'charset': 'utf8',
        }
        return config_dict

class DataBase:
    def __init__(self, config_dict):
        self.config_dict = config_dict
        self.conn = pymysql.connect(**config_dict)

    def query(self, sql, values=None):
        with self.conn.cursor() as cursor:
            if values:
                cursor.execute(sql, values)
            else:
                cursor.execute(sql)

            if 'select' in sql.lower():
                record = cursor.fetchone()
                while record:
                    yield record
                    record = cursor.fetchone()
            else:
                self.conn.commit()

            cursor.close()

    def close(self):
        self.conn.close()

directory = os.path.dirname(__file__)
path = os.path.join(directory, 'ssq', 'settings.ini')

config = Config()
config.read(path)
config_dict = config.get_config()


if __name__ == "__main__":
    conn = DataBase(config_dict)

    sql = """SELECT * FROM ssq WHERE id < 3"""
    records = conn.query(sql)
    for record in records:
        print(record)

    conn.close()

